const { Blog, User } = require("./model");

!(async function(){
    /*
    const zhangsan = await User.findOne({
        where: {
            userName: 'zhangsan'
        }
    })

    //findOne 查寻一条记录 sql语句是limit: 1
    console.log('zhangsan', zhangsan.dataValues)
*/
 /*
    // 查询特定的列
    const zhangsanName = await User.findOne({

        //不写attributes会把所有的列都显示  
        attributes: ['userName','nickName'],
        where: {
            userName: 'zhangsan'
        }
    })
    console.log('zhangsanName', zhangsanName.dataValues)
*/
 
/*
// 查询一个列表
    const zhangsanBlogList = await Blog.findAll({
        where: {
            userId: 1
        },
        order: [
            ['id', 'desc']
        ]
    })
    console.log('zhangsanBlogList',
    zhangsanBlogList.map(blog => blog.dataValues))
    // 数组中的每一项都需要返回一个dataValues
*/

/*
//  分页
    const blogPageList = await Blog.findAll({
        limit: 2,   //限制本次查询2条
        offset: 2,  //跳过多少条
        order: [
            ['id', 'desc']
        ]
    })
    console.log('blogPageList',
    blogPageList.map(blog => blog.dataValues))
*/
/*
    //查询总数
    const blogListAndCount = await Blog.findAndCountAll({
        limit: 2,   //限制本次查询2条
        offset: 0,  //跳过多少条
        order: [
            ['id', 'desc']
        ]    
    })
    console.log(
        'blogListAndCount',
        blogListAndCount.count, // 所有的总数 不考虑分页
        blogListAndCount.rows.map(blog => blog.dataValues)  // 通过分页限制的条数
    )
*/
/*
    // 连表查询
        //查blog表时候，顺便把user表给带出来.即包含 用户的信息，又包含帖子的信息
    const blogListWithUser = await Blog.findAndCountAll({
        order: [
            ['id','desc']
        ],
        include: [
            {
                model: User,
                attributes: ['userName','nickName'],
                where: {
                    userName: 'zhangsan'
                }
            }//attributes是限制条件，不然所有信息 创建 更新时间都有
        ]
    })
    console.log(
        'blogListWithUser',
        blogListWithUser.count, // 查询 zhangsan 的帖子总数
        blogListWithUser.rows.map(blog => {
            const blogVal = blog.dataValues
            blogVal.user = blogVal.user.dataValues
            return blogVal
        })
    )
*/
    // 连表查询 2
    const userListWithBlog = await User.findAndCountAll({
        attributes: ['userName','nickName'],
        include: [
            {
                model: Blog
            }
        ]
    })
    console.log(
        'userListWithBlog',
        userListWithBlog.count,
        userListWithBlog.rows.map(user =>{
            const userVal = user.dataValues
            //console.log('userVal...',userVal)
            //userVal.blog = userVal.blog.dataValues
            userVal.blogs = userVal.blogs.map(blog => blog.dataValues)
            return userVal
        })
    )
})()